//
//  NSMutableAttributedString+HSFeedDetail.m
//  HolyShit
//
//  Created by Robin on 2016/12/3.
//  Copyright © 2016年 HolyShit. All rights reserved.
//

#import "NSMutableAttributedString+HSFeedDetail.h"
#import "NSString+Topic.h"
#import "NSString+Html.h"

@implementation NSMutableAttributedString (HSFeedDetail)

- (void)replaceHtmlTag
{
    NSDate *date = [NSDate date];
    NSRegularExpression *regExp;
    NSArray *matches;
    
    [self replaceTagSpecial];
    [self replaceTagBr];
    //嵌套的p
    regExp = [[NSRegularExpression alloc] initWithPattern:@"</?p>" options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators error:nil];
    matches = [regExp matchesInString:self.string options:0 range:NSMakeRange(0, self.string.length)];
    while (matches.count > 0) {
        [self replaceTagP];
        matches = [regExp matchesInString:self.string options:0 range:NSMakeRange(0, self.string.length)];
    }
    [self replaceTagSpan];
    
#warning 按照现在的写法，先匹配外层再匹配内层显示才ok，\
比如<h1><strong></strong><h1>是正确的，<strong><h1></h1></strong>就需要replacestrong再replaceH \
然后h的嵌套有问题<h1><h2></h2></h1>这样只匹配了最外层
    [self replaceTagH];
    
    regExp = [[NSRegularExpression alloc] initWithPattern:@"</?strong>" options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators error:nil];
    matches = [regExp matchesInString:self.string options:0 range:NSMakeRange(0, self.string.length)];
    while (matches.count > 0) {
        [self replaceTagStrong];
        matches = [regExp matchesInString:self.string options:0 range:NSMakeRange(0, self.string.length)];
    }
    
    [self replaceTagTable];
    [self replaceTagImg];
    
    [self replaceMultibleLine];
    
    NSDate *date0 = [NSDate date];
    NSLog(@"replaceHtml: %f", ([date0 timeIntervalSinceDate:date]));
}

//替换特殊字符
- (void)replaceTagSpecial
{
    NSString *tmpStr = [self.string replaceTagSpecial];
    [self replaceCharactersInRange:self.rangeOfAll withString:tmpStr];
}

- (void)replaceTagBr
{
    NSString *tmpStr = [self.string replaceTagBr];
    [self replaceCharactersInRange:self.rangeOfAll withString:tmpStr];
}

- (void)replaceTagP
{
    NSString *tmpStr = [self.string replaceTagP];
    [self replaceCharactersInRange:self.rangeOfAll withString:tmpStr];
}

- (void)replaceTagSpan
{
    NSString *tmpStr = [self.string replaceTagSpan];
    [self replaceCharactersInRange:self.rangeOfAll withString:tmpStr];
}

- (void)replaceTagImg
{
    NSString *str = self.string;
    NSRegularExpression *regExp = [[NSRegularExpression alloc] initWithPattern:@"<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>" options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray *matches = [regExp matchesInString:str options:0 range:NSMakeRange(0, str.length)];
    if (matches.count < 1) {
        return;
    }
    NSMutableAttributedString *startStr = [NSMutableAttributedString new];
    NSRange startRange = NSMakeRange(0, 0);
    // 遍历匹配后的每一条记录
    for (NSTextCheckingResult *match in matches) {
        NSRange range = [match range];
        if (range.location == NSNotFound) {
            continue;
        }
        //添加无匹配的前面部分
        NSUInteger loc = startRange.location + startRange.length;
        [startStr appendAttributedString:[self attributedSubstringFromRange:NSMakeRange(loc, range.location - loc)]];
        //增加链接
        if (match.numberOfRanges > 1 && [match rangeAtIndex:1].location != NSNotFound) {
            NSString *url = [str substringWithRange:[match rangeAtIndex:1]];//链接
            CGSize imageSize = [url communityImageSize];
            
            YYAnimatedImageView *imgV = [YYAnimatedImageView new];
            imgV.imageType = MYImageTypePic;
            imgV.size = imageSize;
            [imgV my_setImageUrl:url sacleType:MYImageScaleTypePicBig];
            [imgV setOnTouchTapBlock:^(UIImageView *img) {
//                NSLog(@"image's url is : %@", url);
                [[NSNotificationCenter defaultCenter] postNotificationName:HSNotificationTopicImageTabbed object:url];
            }];
            NSMutableAttributedString *subAttr = [NSMutableAttributedString attachmentStringWithContent:imgV contentMode:UIViewContentModeCenter attachmentSize:imageSize alignToFont:self.font alignment:YYTextVerticalAlignmentCenter];
            subAttr.font = self.font;
            subAttr.color = self.color;
            subAttr.lineSpacing = self.lineSpacing;

            [startStr appendAttributedString:subAttr];
        }
        
        //存储上次的位置
        startRange = range;
    }
    //增加无匹配的后面部分
    NSUInteger loc = startRange.location + startRange.length;
    [startStr appendAttributedString:[self attributedSubstringFromRange:NSMakeRange(loc, self.length - loc)]];
    [self replaceCharactersInRange:self.rangeOfAll withAttributedString:startStr];
}

- (void)replaceTagStrong
{
    NSString *str = self.string;
    NSRegularExpression *regExp = [[NSRegularExpression alloc] initWithPattern:@"<strong>([.\\s\\S]*?)</strong>" options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators error:nil];
    NSArray *matches = [regExp matchesInString:str options:0 range:NSMakeRange(0, str.length)];
    if (matches.count < 1) {
        return;
    }
    NSMutableAttributedString *startStr = [NSMutableAttributedString new];
    NSRange startRange = NSMakeRange(0, 0);
    // 遍历匹配后的每一条记录
    for (NSTextCheckingResult *match in matches) {
        NSRange range = [match range];
        if (range.location == NSNotFound) {
            continue;
        }
        //添加无匹配的前面部分
        NSUInteger loc = startRange.location + startRange.length;
        [startStr appendAttributedString:[self attributedSubstringFromRange:NSMakeRange(loc, range.location - loc)]];
        //加粗文本
        if (match.numberOfRanges > 1 && [match rangeAtIndex:1].location != NSNotFound) {
            NSMutableAttributedString *subAttrStr = [[NSMutableAttributedString alloc] initWithAttributedString:[self attributedSubstringFromRange:[match rangeAtIndex:1]]];
            subAttrStr.font = MYBoldFont(subAttrStr.font.pointSize);
            [startStr appendAttributedString:subAttrStr];
        }
        //存储上次的位置
        startRange = range;
    }
    //增加无匹配的后面部分
    NSUInteger loc = startRange.location + startRange.length;
    [startStr appendAttributedString:[self attributedSubstringFromRange:NSMakeRange(loc, self.length - loc)]];
    [self replaceCharactersInRange:self.rangeOfAll withAttributedString:startStr];
}

- (void)replaceTagH
{
    NSString *str = self.string;
    NSRegularExpression *regExp = [[NSRegularExpression alloc] initWithPattern:@"<h([1-6])>([.\\s\\S]*?)</h[1-6]>" options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray *matches = [regExp matchesInString:str options:0 range:NSMakeRange(0, str.length)];
    if (matches.count < 1) {
        return;
    }
    NSMutableAttributedString *startStr = [NSMutableAttributedString new];
    NSRange startRange = NSMakeRange(0, 0);
    // 遍历匹配后的每一条记录
    for (NSTextCheckingResult *match in matches) {
        NSRange range = [match range];
        if (range.location == NSNotFound) {
            continue;
        }
        //添加无匹配的前面部分
        NSUInteger loc = startRange.location + startRange.length;
        [startStr appendAttributedString:[self attributedSubstringFromRange:NSMakeRange(loc, range.location - loc)]];
        //加粗文本
        if (match.numberOfRanges > 1 && [match rangeAtIndex:1].location != NSNotFound) {
            NSString *fontSize = [str substringWithRange:[match rangeAtIndex:1]];
            if([fontSize isNotBlank] &&match.numberOfRanges > 2 && [match rangeAtIndex:2].location != NSNotFound){
                //设定h4为正常大小
                NSInteger sizeDiff = (fontSize.integerValue - 4) * 2;
                NSMutableAttributedString *subAttrStr = [[NSMutableAttributedString alloc] initWithAttributedString:[self attributedSubstringFromRange:[match rangeAtIndex:2]]];
                if (subAttrStr.font.isBold) {
                    subAttrStr.font = MYBoldFont(subAttrStr.font.pointSize - sizeDiff);
                }
                else{
                    subAttrStr.font = MYFont(subAttrStr.font.pointSize - sizeDiff);
                }
                [subAttrStr insertString:@"\n" atIndex:0];
                [subAttrStr appendString:@"\n"];
                [startStr appendAttributedString:subAttrStr];
            }
        }
        //存储上次的位置
        startRange = range;
    }
    //增加无匹配的后面部分
    NSUInteger loc = startRange.location + startRange.length;
    [startStr appendAttributedString:[self attributedSubstringFromRange:NSMakeRange(loc, self.length - loc)]];
    [self replaceCharactersInRange:self.rangeOfAll withAttributedString:startStr];
}

- (void)replaceTagTable
{
    NSString *str = self.string;
    NSRegularExpression *regExp = [[NSRegularExpression alloc] initWithPattern:@"<table>([.\\s\\S]*?)</table>" options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators error:nil];
    NSArray *matches = [regExp matchesInString:str options:0 range:NSMakeRange(0, str.length)];
    if (matches.count < 1) {
        return;
    }
    
    NSMutableAttributedString *startStr = [NSMutableAttributedString new];
    NSRange startRange = NSMakeRange(0, 0);
    for (NSTextCheckingResult *match in matches) {
        NSRange range = [match range];
        if (range.location == NSNotFound) {
            continue;
        }
        //添加无匹配的前面部分
        NSUInteger loc = startRange.location + startRange.length;
        [startStr appendAttributedString:[self attributedSubstringFromRange:NSMakeRange(loc, range.location - loc)]];
        [startStr appendString:@"\n"];
        //这边开始添加tr和td
        if (match.numberOfRanges > 1) {
            NSMutableAttributedString *subAttrStr = [[NSMutableAttributedString alloc] initWithAttributedString:[self attributedSubstringFromRange:[match rangeAtIndex:1]]];
            
            //进行转换，如果只有一列td就直接显示
            BOOL moreThanOneTd = NO;
            NSAttributedString *str = [self trTdAttrWithAttr:subAttrStr moreThanOneTd:&moreThanOneTd];
            if (moreThanOneTd) {
                [startStr appendAttributedString:str];
            }
            else{
                NSArray<NSString *> *orign = @[@"<tr>", @"<td>", @"<tbody>", @"</tr>", @"</td>", @"</tbody>"];
                NSArray<NSString *> *result = @[@"", @"", @"", @"\n", @"\n", @"\n"];
                __block NSString *resultStr = subAttrStr.string;
                [orign enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    resultStr = [resultStr replaceRegStr:obj WithStr:result[idx]];
                }];
                [subAttrStr replaceCharactersInRange:subAttrStr.rangeOfAll withString:resultStr];
                [startStr appendAttributedString:subAttrStr];
            }
        }
        [startStr appendString:@"\n"];
        //存储上次的位置
        startRange = range;
    }
    //增加无匹配的后面部分
    NSUInteger loc = startRange.location + startRange.length;
    [startStr appendAttributedString:[self attributedSubstringFromRange:NSMakeRange(loc, self.length - loc)]];
    [self replaceCharactersInRange:self.rangeOfAll withAttributedString:startStr];
}

- (NSMutableAttributedString *)trTdAttrWithAttr:(NSAttributedString *)attrStr moreThanOneTd:(BOOL *)moreThanOneTd
{
    NSMutableAttributedString *attr = [NSMutableAttributedString new];
    NSRegularExpression *regExp = [[NSRegularExpression alloc] initWithPattern:@"<tr>([.\\s\\S]*?)</tr>" options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators error:nil];
    NSArray *matches = [regExp matchesInString:attrStr.string options:0 range:NSMakeRange(0, attrStr.string.length)];
    if (matches.count < 1) {
        return attr;
    }
    
    for (NSTextCheckingResult *match in matches) {
        NSRange range = [match range];
        if (range.location == NSNotFound || match.numberOfRanges < 2) {
            continue;
        }
        //解析td
        regExp = [[NSRegularExpression alloc] initWithPattern:@"<td>([.\\s\\S]*?)</td>" options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators error:nil];
        NSArray *matches2 = [regExp matchesInString:attrStr.string options:0 range:[match rangeAtIndex:1]];
        NSUInteger count = matches2.count;
        if (count < 1) {
            continue;
        }
        else if(count > 1){
            *moreThanOneTd = YES;
        }
        
        UIView *trView = [UIView new];
        trView.layer.borderWidth = 1;
        trView.layer.borderColor = HEXCOLOR(HSColorGray).CGColor;
        trView.size = CGSizeMake(ScreenWidth - 20, 15);
        CGFloat wid = trView.width / count;
        NSUInteger idx = 0;
        for (NSTextCheckingResult *match2 in matches2) {
            NSRange range2 = [match2 range];
            if (range2.location == NSNotFound || match2.numberOfRanges < 2) {
                continue;
            }
            
            NSMutableAttributedString *tmpAttr = [[NSMutableAttributedString alloc] initWithAttributedString:[attrStr attributedSubstringFromRange:[match2 rangeAtIndex:1]]];
            
            YYLabel *lb = [[YYLabel alloc] initWithFrame:CGRectMake(idx * wid + 6, 0, wid - 6, 0)];
            lb.textColor = HEXCOLOR(HSColorBlack);
            lb.numberOfLines = 0;
            YYTextLayout *layout = [YYTextLayout layoutWithContainer:[YYTextContainer containerWithSize:CGSizeMake(wid - 6, CGFLOAT_MAX)] text:tmpAttr];
            lb.textLayout = layout;
            lb.height = layout.textBoundingSize.height + 12;
            [trView addSubview:lb];
            if (idx < count - 1) {
                UIView *line = [[UIView alloc] initWithFrame:CGRectMake((idx + 1) * wid - 1, 0, 1, lb.height)];
                line.backgroundColor = HEXCOLOR(HSColorGray);
                [trView addSubview:line];
            }
            if (trView.height < lb.height) {
                trView.height = lb.height;
            }
            ++idx;
        }
        [trView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.height = trView.height;
        }];
        NSMutableAttributedString *subAttr = [NSMutableAttributedString attachmentStringWithContent:trView contentMode:UIViewContentModeCenter attachmentSize:trView.size alignToFont:self.font alignment:YYTextVerticalAlignmentCenter];
        subAttr.font = self.font;
        subAttr.color = self.color;
        subAttr.lineSpacing = -1;
        [attr appendAttributedString:subAttr];
    }
    
    return attr;
}

/**
 html的换行只是换行，ios的换行是换段
 所以匹配完成后为何合理一些去掉后面一个换行
 当然，如果本来就有\n\n的就对不起咯😝，反正也看不出来
 */
- (void)replaceMultibleLine
{
    NSString *str = self.string;
    NSRegularExpression *regExp = [[NSRegularExpression alloc] initWithPattern:@"\n\n" options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators error:nil];
    NSArray *matches = [regExp matchesInString:str options:0 range:NSMakeRange(0, str.length)];
    if (matches.count < 1) {
        return;
    }
    NSMutableAttributedString *startStr = [NSMutableAttributedString new];
    NSRange startRange = NSMakeRange(0, 0);
    // 遍历匹配后的每一条记录
    for (NSTextCheckingResult *match in matches) {
        NSRange range = [match range];
        if (range.location == NSNotFound) {
            continue;
        }
        //添加无匹配的前面部分
        NSUInteger loc = startRange.location + startRange.length;
        [startStr appendAttributedString:[self attributedSubstringFromRange:NSMakeRange(loc, range.location - loc + 1)]];
        //存储上次的位置
        startRange = range;
    }
    //增加无匹配的后面部分
    NSUInteger loc = startRange.location + startRange.length;
    [startStr appendAttributedString:[self attributedSubstringFromRange:NSMakeRange(loc, self.length - loc)]];
    [self replaceCharactersInRange:self.rangeOfAll withAttributedString:startStr];
}

@end
